/**
 * 自定义svg格式加载
 */
Vue.component('SvgIcon', {
    template: `<svg :style="{ width, height }">
        <use :xlink:href="prefix + name" :fill="color"></use>
    </svg>`,
    props: {
        prefix: {
            type: String,
            default: '#icon-',
        },
        name: String,
        color: {
            type: String,
            default: '',
        },
        width: {
            type: String,
            default: '16px',
        },
        height: {
            type: String,
            default: '16px',
        },
    },
})
/**
 * 上传图片
 */
Vue.component('yl-upload', {
    template: `<div>
    <div class="preview" v-if="Picture_URL">
        <el-image class="el-upload-list__item-thumbnail" style="width: 148px; height: 148px" :src="base64?Picture_URL:base + Picture_URL" fit="contain"></el-image>
        <span class="el-upload-list__item-actions">
            <span @click="handlePictureCardPreview(base64?Picture_URL:base + Picture_URL)"><i class="el-icon-zoom-in"></i></span>
            <span @click="handleRemove"><i class="el-icon-delete"></i></span>
        </span>
    </div>
    <el-upload :disabled="loading" v-else class="upload-demo" :show-file-list="false" :on-change="upload"
        list-type="picture-card" action="" accept="image/*" :auto-upload="false">
        <i slot="default" :class="loading?'el-icon-loading':'el-icon-plus'"></i>
        <div v-if="!unslider" class="el-upload__tip" slot="tip">
            <div v-show="quality < 100">当前图片压缩至{{quality}}%</div>
            <el-slider :min="1" style="width:148px" v-model="quality" :format-tooltip="formatTooltip"></el-slider>
        </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <el-image width="100%" fit="contain" :src="dialogImageUrl">
    </el-dialog></div>`,
    props: {
        value: {
            type: String,
            default: ''
        },
        base: {
            type: String,
            default: ''
        },
        base64: {
            type: Boolean,
            default: false
        },
        unslider:{
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            Picture_URL: this.value,
            loading: false,
            dialogVisible: false,
            dialogImageUrl: '',
            quality: 100,
        }
    },
    watch: {
        value(newVal) {
            this.Picture_URL = newVal
        },
        Picture_URL(newVal) {
            this.$emit('input', newVal);
        }
    },
    methods: {
        formatTooltip(val) {
            return '图片压缩比例：' + val + '%';
        },
        upload({ raw }) {
            const that = this;
            new Compressor(raw, {
                quality: that.quality / 100,
                success(file) {
                    that.loading = true;
                    const formData = new FormData();
                    formData.append('file', file, file.name);
                    let oFileReader = new FileReader();
                    oFileReader.readAsDataURL(file);
                    oFileReader.onload = function (e) {
                        if (!that.base64) {
                            $.ajax({
                                headers: requestHeaders("JSON"),
                                url: `${BASE_URL2}/generalBusiness/generalSaveFilesAsImage`,
                                type: 'POST',
                                data: JSON.stringify({
                                    Data: e.target.result,
                                    DataLength: file.size,
                                    FileName: file.name
                                }),
                                success: function (Result) {
                                    if (Result.Status == "success") {
                                        that.Picture_URL = Result.FileName
                                        that.$message.success('上传成功')
                                    } else {
                                        that.$message.error('上传失败')
                                    }
                                },
                                complete: function (XMLHttpRequest) {
                                    that.loading = false
                                    requestPretreatment(XMLHttpRequest);
                                },
                                dataType: "json"
                            });
                        } else {
                            that.Picture_URL = e.target.result;
                            that.loading = false
                        }
                    }
                },
                error(err) {
                    console.log(err.message);
                },
            });
        },
        handlePictureCardPreview(Val) {
            this.dialogVisible = true
            this.dialogImageUrl = Val
        },
        handleRemove() {
            this.Picture_URL = ''
        }
    }
})

Vue.component('yl-page-header', {
    template:`<div style="height: 20px;">
    <div style="border-bottom: 1px solid rgb(245, 245, 245); position: fixed;top: 0;left: 0; height: 40px; display: flex; align-items: center; background:#fff; z-index: 2000; width: 100%;">
        <div style="margin-left: 20px;display: flex;line-height: 24px;">
            <div class="el-page-header__left" @click="window.history.back()" >
                <i class="el-icon-back"></i>
                <div class="el-page-header__title" style="color: rgb(105, 105, 105);">{{title}}</div>
            </div>
            <div style="font-size: 16px; font-weight:700; color: rgb(105, 105, 105);">{{content}}</div>
        </div>
    </div></div>`,
    props:{
        content:{
            type: String,
            default: ''
        },
        title:{
            type:String,
            default: '返回'
        }
    }
})

/**
* Countdown 倒计时
* @description 倒计时组件
* @property {String} backgroundColor 背景色
* @property {String} color 文字颜色
* @property {Number} day 天数
* @property {Number} hour 小时
* @property {Number} minute 分钟
* @property {Number} second 秒
* @property {Number} timestamp 时间戳
* @property {Boolean} showDay = [true|false] 是否显示天数
* @property {Boolean} showHour = [true|false] 是否显示小时
* @property {Boolean} showMinute = [true|false] 是否显示分钟
* @property {Boolean} show-colon = [true|false] 是否以冒号为分隔符
* @property {String} splitorColor 分割符号颜色
* @event {Function} timeup 倒计时时间到触发事件
* @example <countdown :day="1" :hour="1" :minute="12" :second="40"></countdown>
*/
Vue.component('countdown', {
    template: `<div style="display: flex; flex-direction: row; justify-content: flex-start; align-items: center;">
    <span v-if="showDay" :style="[timeStyle]" style="border-radius: 3px; text-align: center; font-size: 14px;">{{ d }}</span>
    <span v-if="showDay" :style="[splitorStyle]" style="margin: 0 2px; font-size: 14px; color: #333;">{{ dayText }}</span>
	<span v-if="showHour" :style="[timeStyle]" style="border-radius: 3px; text-align: center; font-size: 14px;">{{ h }}</span>
	<span v-if="showHour" :style="[splitorStyle]" style="margin: 0 2px; font-size: 14px; color: #333;">{{ showColon ? ':' : hourText }}</span>
	<span v-if="showMinute" :style="[timeStyle]" style="border-radius: 3px; text-align: center; font-size: 14px;">{{ i }}</span>
	<span v-if="showMinute" :style="[splitorStyle]" style="margin: 0 2px; font-size: 14px; color: #333;">{{ showColon ? ':' : minuteText }}</span>
	<span :style="[timeStyle]" style="border-radius: 3px; text-align: center; font-size: 14px;">{{ s }}</span>
	<span v-if="!showColon" :style="[splitorStyle]" style="margin: 0 2px; font-size: 14px; color: #333;">{{secondText}}</span>
    </div>`,
    props: {
        showDay: {
            type: Boolean,
            default: true
        },
        showHour: {
            type: Boolean,
            default: true
        },
        showMinute: {
            type: Boolean,
            default: true
        },
        showColon: {
            type: Boolean,
            default: true
        },
        start: {
            type: Boolean,
            default: true
        },
        backgroundColor: {
            type: String,
            default: ''
        },
        color: {
            type: String,
            default: '#333'
        },
        fontSize: {
            type: Number,
            default: 12
        },
        splitorColor: {
            type: String,
            default: '#333'
        },
        day: {
            type: Number,
            default: 0
        },
        hour: {
            type: Number,
            default: 0
        },
        minute: {
            type: Number,
            default: 0
        },
        second: {
            type: Number,
            default: 0
        },
        timestamp: {
            type: Number,
            default: 0
        },
        update: {
            type: Boolean,
            default: false
        },
        lang: {
            type: String,
            default: 'zh-Hans'
        }
    },
    data() {
        return {
            timer: null,
            syncFlag: false,
            d: '00',
            h: '00',
            i: '00',
            s: '00',
            leftTime: 0,
            seconds: 0,
            t: {
                "zh-Hans": {
                    "countdown.day": "天",
                    "countdown.h": "时",
                    "countdown.m": "分",
                    "countdown.s": "秒"
                },
                "en": {
                    "countdown.day": "day",
                    "countdown.h": "h",
                    "countdown.m": "m",
                    "countdown.s": "s"
                },
                "zh-Hant": {
                    "countdown.day": "天",
                    "countdown.h": "時",
                    "countdown.m": "分",
                    "countdown.s": "秒"
                }

            }
        }
    },
    computed: {
        dayText() {
            return this.t[this.lang]["countdown.day"]
        },
        hourText(val) {
            return this.t[this.lang]["countdown.h"]
        },
        minuteText(val) {
            return this.t[this.lang]["countdown.m"]
        },
        secondText(val) {
            return this.t[this.lang]["countdown.s"]
        },
        timeStyle() {
            const { color, backgroundColor, fontSize } = this;
            return {
                color,
                backgroundColor,
                fontSize: `${fontSize}px`,
                width: `${fontSize * 22 / 14}px`, // 按字体大小为 14px 时的比例缩放
                lineHeight: `${fontSize * 20 / 14}px`,
                borderRadius: `${fontSize * 3 / 14}px`,
            }
        },
        splitorStyle() {
            const { splitorColor, fontSize, backgroundColor } = this
            return {
                color: splitorColor,
                fontSize: `${fontSize * 12 / 14}px`,
                margin: backgroundColor ? `${fontSize * 4 / 14}px` : ''
            }
        }
    },
    watch: {
        day(val) {
            this.changeFlag()
        },
        hour(val) {
            this.changeFlag()
        },
        minute(val) {
            this.changeFlag()
        },
        second(val) {
            this.changeFlag()
        },
        start: {
            immediate: true,
            handler(newVal, oldVal) {
                if (newVal) {
                    this.startData();
                } else {
                    if (!oldVal) return
                    clearInterval(this.timer)
                }
            }
        },
    },
    created: function (e) {
        this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
        this.countDown()
    },
    methods: {
        toSeconds(timestamp, day, hours, minutes, seconds) {
            if (timestamp) {
                return timestamp - parseInt(new Date().getTime() / 1000, 10)
            }
            return day * 60 * 60 * 24 + hours * 60 * 60 + minutes * 60 + seconds
        },
        timeUp() {
            clearInterval(this.timer)
            this.$emit('timeup')
        },
        countDown() {
            let seconds = this.seconds
            let [day, hour, minute, second] = [0, 0, 0, 0]
            if (seconds > 0) {
                day = Math.floor(seconds / (60 * 60 * 24))
                hour = Math.floor(seconds / (60 * 60)) - (day * 24)
                minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
                second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
            } else {
                this.timeUp()
            }
            if (day < 10) {
                day = '0' + day
            }
            if (hour < 10) {
                hour = '0' + hour
            }
            if (minute < 10) {
                minute = '0' + minute
            }
            if (second < 10) {
                second = '0' + second
            }
            this.d = day
            this.h = hour
            this.i = minute
            this.s = second
        },
        startData() {
            this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
            if (this.seconds <= 0) {
                this.seconds = this.toSeconds(0, 0, 0, 0, 0)
                this.countDown()
                return
            }
            clearInterval(this.timer)
            this.countDown()
            this.timer = setInterval(() => {
                this.seconds--
                if (this.seconds < 0) {
                    this.timeUp()
                    return
                }
                this.countDown()
            }, 1000)
        },
        changeFlag() {
            if (!this.syncFlag || this.update) {
                this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
                this.startData();
                this.syncFlag = true;
            }
        }
    }
})

/**
 * 富文本
 */
Vue.component('yl-text-editor', {
    template: `<div id="editor—wrapper">
        <div id="toolbar-container"><!-- 工具栏 --></div>
        <div id="editor-container"><!-- 编辑器 --></div>
    </div>`,
    props: {
        value: {
            type: String,
            default: '',
        },
        placeholder: {
            type: String,
            default: '请填写富文本内容...'
        },
        max: {
            type: Number,
            default: 0,
        },
        type: {
            type: String,
            default: 'default'
        },
        disabled: {
            type: Boolean,
            default: false,
        }
    },
    data() {
        return {
            editor: null,//核心
            html: this.value,//文本内容
        }
    },
    watch: {
        html(newVal) {//组件双向绑定
            this.$emit('input', newVal);
        },
        value(newVal) {//更新文本内容
            if (this.editor.getHtml() != newVal) {
                this.editor.setHtml(newVal);
            }
        },
        disabled(disabled) {//动态禁用状态
            if (this.editor.isDisabled() && !disabled) {
                this.editor.enable();
            } else if (!this.editor.isDisabled() && disabled) {
                this.editor.disable();
            }
        }
    },
    computed: {
        maxLength() {//最大文字限制，默认0为无限制
            return this.max == 0 ? {} : { maxLength: this.max };
        },
        mode() {//是否开启简洁模式
            return this.type == 'default' || this.type == 'simple' ? this.type : 'default';
        }
    },
    methods: {
        init() {//初始化
            const { createEditor, createToolbar } = window.wangEditor
            const editorConfig = {
                placeholder: this.placeholder,
                ...this.maxLength,
                readOnly: this.disabled,
                onChange: (editor) => {
                    this.html = editor.getHtml();
                },
                onDestroyed(editor) {
                    editor.destroy();
                }
            }
            const editor = createEditor({
                selector: '#editor-container',
                html: '<p><br></p>',
                config: editorConfig,
                mode: this.mode,
            })
            const toolbarConfig = {}
            const toolbar = createToolbar({
                editor: editor,
                selector: '#toolbar-container',
                config: toolbarConfig,
                mode: this.mode,
            })
            this.editor = Object.seal(editor);
        }
    },
    mounted() {
        this.init()
    }
})

/**
 * 手机模拟样式
 */
Vue.component('mobile', {
    template: `<div :style="showMobilePreview">
    <div :style="mobile_preview_header"><i :style='mobile_preview_header_icon'></i></div>
    <div :style='mobile_preview_frame'><iframe id="Mobile" :src="src" :style='YuFrameMobilePreview' name='YuFrameMobilePreview' ></iframe></div>
    <div :style='mobile_preview_footer'><i :style='mobile_preview_footer_icon'></i></div>
    </div>`,
    props: {
        value: {
            type: String,
            default: ''
        },
        query: {
            type: Object,
            default: function () {
                return {}
            }
        },
        base: {
            type: String,
            default:'',
        },
    },
    data() {
        return {
            url: this.value,
        }
    },
    computed: {
        src() {
            if (this.url) {
                let str = "";
                for (let key in this.query) {
                    if (str) {
                        str = str + "&" + key + "=" + this.query[key]
                    } else {
                        str = "?" + key + "=" + this.query[key]
                    }
                }
                return this.base + this.url + str;
            } else {
                return ""
            }
        },
        showMobilePreview() {//样式
            return {
                width: '391px',
                height: '768px',
                opacity: 1,
                textAlign: 'center'
            }
        },
        mobile_preview_header() {
            return {
                display: 'block',
                height: '40px',
                width: '387px',
                background: '#eeeff2',
                textAlign: 'center',
                lineHeight: '40px',
                borderRadius: '50px 50px 0 0'
            }
        },
        mobile_preview_header_icon() {
            return {
                display: 'inline-block',
                width: '65px',
                height: '10px',
                background: '#c8c9cc',
                borderRadius: '9px',
                verticalAlign: 'middle',
                marginTop: '18px',
            }
        },
        mobile_preview_frame() {
            return {
                width: '375px',
                minHeight: '294px',
                height: '667px',
                maxHeight: 'calc(100vh - 166px)',
                top: '40px',
                border: '6px solid #eeeff2',
                backgroundColor: '#fff',
                display: 'block',
            }
        },
        YuFrameMobilePreview() {
            return {
                border: 'none',
                width: '375px',
                height: '100%',
                scrollbarWidth: 'thin',
                scrollbarColor: '#888 #f1f1f1'
            }
        },
        mobile_preview_footer() {
            return {
                display: 'block',
                height: '52px',
                width: '387px',
                backgroundColor: '#eeeff2',
                textAlign: 'center',
                lineHeight: '45px',
                borderRadius: '0 0 50px 50px '
            }
        },
        mobile_preview_footer_icon() {
            return {
                display: 'inline-block',
                width: '43px',
                height: '43px',
                background: '#c8c9cc',
                borderRadius: '50%',
                verticalAlign: 'middle',
            }
        }
    },
    watch: {
        value(newVal) {
            this.url = newVal
        },
        url(newVal) {
            this.$emit('input', newVal);
        }
    },
})

/**
 * 模拟uniapp的uni.showToast，不带icon
 */
const showToast = Vue.component('show-toast', {
    template: `<div :style="style" v-show="show">
    <div :style="textStyle">
        {{title}}
    </div></div>`,
    props: {
        title: {
            type: String,
            default: ''
        },
        show: {
            type: Boolean,
            default: false
        }
    },
    computed: {
        style() {
            return {
                position: 'fixed',
                top: 0,
                left: 0,
                width: '100%',
                height: '100%',
                Zindex: 100000,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
            }
        },
        textStyle() {
            return {
                background: '#000',
                opacity: '.65',
                color: '#fff',
                padding: '10px 20px',
                width: '40%',
                fontSize: '14px',
                borderRadius: '5px',
                textAlign: 'center'
            }
        },
    },
})

/**
 * 挂载到Vue组件上
 */
Vue.use({
    install(Vue) {
        let Com = Vue.extend(showToast); //拓展方法，showToast是独立的组件，extend的作用是将showToast与Vue关联起来
        let vm = new Com().$mount(); //组件实例化，使用$mount可以获取showToast组件vm层
        document.body.appendChild(vm.$el);

        Vue.prototype.$showToast = function (data) {
            if (isNaN(data.duration)) {
                data.duration = 1500
            }
            vm.show = true;
            vm.title = data.title;
            const timer = setTimeout(() => {
                vm.show = false;
                clearTimeout(timer);
            }, data.duration)
        }
    }
});

/**
 * 上传筛选成功，失败数据的通用部分
 */
const importMixin = {
    data(){
        return {
            filter:'',
        }
    },
    computed:{
        Data(){
            if (this.filter=='1') {
                return this.tableData.filter(i=>i.isStatus == '1')
            }else if (this.filter=='2') {
                return this.tableData.filter(i=>i.isStatus == '2')
            }else {
                return this.tableData
            }
            
        }
    },
    methods:{
        handleTab(id){
            if (this.filter!=''&&this.filter==id) {
                this.filter=''
            }else{
                this.filter=id
            }
        },
    }
}